package com.can.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.can.reggie.common.R;
import com.can.reggie.dto.DishDto;
import com.can.reggie.entity.Category;
import com.can.reggie.entity.Dish;
import com.can.reggie.entity.DishFlavor;
import com.can.reggie.entity.SetmealDish;
import com.can.reggie.service.CategoryService;
import com.can.reggie.service.DishFlavorService;
import com.can.reggie.service.DishService;
import com.can.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/*
 * 菜品和菜品口味的管理
 * */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //新增菜品和口味
        dishService.saveWithFlavor(dishDto);

        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清理某个分类下的缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }


    /**
     * //key: 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.eq(Dish::getIsDeleted, 0);
        lqw.like(name != null, Dish::getName, name);
        //添加排序条件
        lqw.orderByDesc(Dish::getUpdateTime);
        //执行查询
        Page<Dish> dishPage = dishService.page(pageInfo, lqw);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");


        //创建一个空的dishDto的list
        List<DishDto> dtoRecords = new ArrayList<>();

        //遍历获取每一条dish记录
        List<Dish> records = dishPage.getRecords();
        for (Dish record : records) {

            //new 一个 new_dishDto对象
            DishDto new_dishDto = new DishDto();

            //把dish记录拷贝进 new_dishDto对象
            BeanUtils.copyProperties(record, new_dishDto);

            //获取dish记录中的菜品id查询其菜品name,封装进new_dishDto
            Category category = categoryService.getById(record.getCategoryId());
            String categoryName = category.getName();
            new_dishDto.setCategoryName(categoryName);

            //把new_dishDto对象封装进DishDto的list中
            dtoRecords.add(new_dishDto);
        }

        //把创建的dishDto的list 封装进dishDtoPage
        dishDtoPage.setRecords(dtoRecords);

        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }


    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //修改菜品和口味
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清理某个分类下的缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }


    /**
     * 根据分类id,查询对应菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //new 一个 DishDto 集合
        List<DishDto> dishDtoList = null;

        //拼接本次请求所对应的key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key); //key 如果这里查询为空,则集合为null

        if (dishDtoList != null) {
            //如果缓存中获取到了数据,则直接返回,无需查寻数据库
            return R.success(dishDtoList);
        }

        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据分类id查询
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //根据菜品名字查询
        lqw.like(dish.getName() != null, Dish::getName, dish.getName());
        //状态为售卖中
        lqw.eq(Dish::getStatus, 1);
        //是否被隐藏
        lqw.eq(Dish::getIsDeleted, 0);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(lqw);

        //new 一个 DishDto 集合
        dishDtoList = new ArrayList<>();//key 如果在175行定义集合,181行则会赋值为null,218行:dishDtoList.add(dishDto)则会空指针异常

        //对查询出来的 dishList进行遍历
        for (Dish new_dish : dishList) {
            //new 一个 dishDto对象,将new_dish拷贝进去
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(new_dish, dishDto);

            //根据new_dish中的id,查询对应的口味
            LambdaQueryWrapper<DishFlavor> new_lqw = new LambdaQueryWrapper<>();
            new_lqw.eq(DishFlavor::getDishId, new_dish.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(new_lqw);
            //将flavorList封装进dishDto
            dishDto.setFlavors(flavorList);

            //再将dishDto对象 ,添加至 dishDtoList
            dishDtoList.add(dishDto);
        }

        //如果redis中不存在,则去数据库中查询,同时将结果缓存到Redis
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }


    /**
     * //key 返回Dish不能满足需求了,需要改造成返回DishDto
     * 根据分类id,查询对应菜品
     *
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //根据分类id查询
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //根据菜品名字查询
        lqw.like(dish.getName() != null, Dish::getName, dish.getName());
        //状态为售卖中
        lqw.eq( Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(lqw);
        return R.success(dishList);
    }*/


    /**
     * 根据id修改菜品状态
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/{stateId}")
    public R<String> statusUpdate(Long[] ids, @PathVariable Integer stateId) {
        //TODO 目前不考虑缓存
//        for (Long id : ids) {
//            //根据id,查询CategoryId
//            Dish dish = dishService.getById(id);
//
//            //清理某个分类下的缓存数据
//            String key = "dish_" + dish.getCategoryId() + "_1";
//            redisTemplate.delete(key);
//        }

        return dishService.stateUpdate(ids, stateId);
    }


    /**
     * 根据id删除菜品(更改菜品id_delete状态,和菜品口味表id_delete状态)
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids) {

        return dishService.deleteDish(ids);
    }
}
